package com.takeeasy.platform.persistence;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.commons.dbcp.BasicDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ConnectionPool {
	public static BasicDataSource dataSource;
	private static Logger logger = LoggerFactory
			.getLogger(ConnectionPool.class);

	public static synchronized Connection getConnection() {
		try {
			return dataSource.getConnection();
		} catch (SQLException e) {
			logger.error("获取数据链接失败！" + e.getMessage());
		}
		return null;
	}

	public static void setDataSource(BasicDataSource dataSource) {
		synchronized (dataSource) {
			ConnectionPool.dataSource = dataSource;
		}
	}

	public static void testConnection() {
		logger.debug("测试数据库连接...");
		if (ConnectionPool.dataSource != null) {
			Connection conn = ConnectionPool.getConnection();
			try {
				if (conn == null) {
					// logger.error("无法获取数据库连接，请检查数据库配置！");
					return;
				}
				Statement stat = conn.createStatement();
				boolean result = stat.execute("select now()");
				if (!result) {
					throw new RuntimeException("");
				} else {
					logger.info("数据库连接成功...");
				}
			} catch (SQLException e) {
				try {
					conn.close();
				} catch (SQLException e1) {
					logger.error("数据库连接失败：" + e1.getMessage());
				}
				logger.error("数据库连接失败：" + e.getMessage());
			}
		} else {

		}
	}
}
